package xyz.xcvu.ma2.module;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.region.Region;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.annotation.MagicModule;
import org.ssssssss.script.annotation.Comment;
import xyz.xcvu.ma2.utils.MimeUtil;

import java.io.IOException;
import java.io.InputStream;

@Component
@MagicModule("cos")
public class Cos {
    private static final Log log = LogFactory.get();

    public COSClient getClient(
            @Comment("accessKey") String accessKey,
            @Comment("secretKey") String secretKey,
            @Comment("ap-chongqing") String regionName
    ){
        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(accessKey, secretKey);
        // 2 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region(regionName));
        // 3 生成cos客户端
        return new COSClient(cred, clientConfig);
    }

    public String upload(
            @Comment("上传对象")COSClient cosClient,
            @Comment("桶名称") String bucketName,
            @Comment("文件输入流")InputStream inputStream,
            @Comment("上传文件的路径")String path
    ){
        path = path.startsWith("/") ? path.substring(1) : path;
        ObjectMetadata objectMetadata = new ObjectMetadata();
        long size = 0;
        try {
            size = inputStream.available();
        } catch (IOException e) {
            log.warn(e.getMessage());
        }
        String contentType = MimeUtil.getMimeType(path);
        objectMetadata.setContentLength(size);//文件的大小
        objectMetadata.setContentType(contentType);//文件的类型
        // 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）。
        cosClient.putObject(bucketName,path,inputStream,objectMetadata);
        // 关闭OSSClient。
        cosClient.shutdown();
        return "/" + path;
    }
}
